<template>
  <!-- 附件区域 - 现代美观设计 -->
  <view class="attachments-section">
    <view class="section-header">
      <view class="section-title-wrapper">
        <text class="section-title">{{ title }}</text>
        <text v-if="modelValue.length === 0 && required" class="required-mark">*</text>
      </view>
      <view class="upload-stats">
        <view
          class="stat-item"
          :class="{ 'limit-reached': isImageLimitReached }"
        >
          <fui-icon
            name="picture"
            :color="isImageLimitReached ? '#c0c4cc' : '#0052d9'"
            :size="20"
          ></fui-icon>
          <text>{{ imageFiles.length }}/{{ maxImageCount }}</text>
        </view>
        <view
          class="stat-item"
          :class="{ 'limit-reached': isFileLimitReached }"
        >
          <fui-icon
            name="order"
            :color="isFileLimitReached ? '#c0c4cc' : '#0052d9'"
            :size="20"
          ></fui-icon>
          <text>{{ documentFiles.length }}/{{ maxFileCount }}</text>
        </view>
        <view
          class="stat-item"
          :class="{ 'limit-reached': isVideoLimitReached }"
        >
          <fui-icon
            name="video"
            :color="isVideoLimitReached ? '#c0c4cc' : '#0052d9'"
            :size="20"
          ></fui-icon>
          <text>{{ videoFiles.length }}/{{ maxVideoCount }}</text>
        </view>
        <view
          class="stat-item"
          :class="{ 'limit-reached': isTotalLimitReached }"
        >
          <fui-icon
            name="formfill"
            :color="isTotalLimitReached ? '#c0c4cc' : '#0052d9'"
            :size="20"
          ></fui-icon>
          <text>{{ modelValue.length }}/{{ maxTotalFiles }}</text>
        </view>
      </view>
    </view>

    <!-- 上传按钮区域 - 更现代的设计 -->
    <view class="upload-triggers-modern">
      <view
        class="trigger-btn"
        @click="handleChooseImage"
        :class="{ disabled: isImageLimitReached }"
      >
        <view class="btn-icon">
          <fui-icon
            name="picture"
            :color="isImageLimitReached ? '#c8c9cc' : '#0052d9'"
            :size="28"
          ></fui-icon>
        </view>
        <text
          class="btn-text"
          :class="{ 'disabled-text': isImageLimitReached }"
          >上传图片</text
        >
      </view>
      <view
        class="trigger-btn"
        @click="handleChooseFile"
        :class="{ disabled: isFileLimitReached }"
      >
        <view class="btn-icon">
          <fui-icon
            name="order"
            :color="isFileLimitReached ? '#c8c9cc' : '#0052d9'"
            :size="28"
          ></fui-icon>
        </view>
        <text
          class="btn-text"
          :class="{ 'disabled-text': isFileLimitReached }"
          >上传文件</text
        >
      </view>
      <view
        class="trigger-btn"
        @click="handleChooseVideo"
        :class="{ disabled: isVideoLimitReached }"
      >
        <view class="btn-icon">
          <fui-icon
            name="video"
            :color="isVideoLimitReached ? '#c8c9cc' : '#0052d9'"
            :size="28"
          ></fui-icon>
        </view>
        <text
          class="btn-text"
          :class="{ 'disabled-text': isVideoLimitReached }"
          >上传视频</text
        >
      </view>
    </view>

    <!-- 空态展示 - 更美观 -->
    <view v-if="!hasAnyFiles" class="empty-attachments-modern">
      <view class="empty-icon">
        <fui-icon name="upload" color="#c0c4cc" size="64"></fui-icon>
      </view>
      <text class="empty-text">暂无附件，请点击上方按钮上传</text>
    </view>

    <!-- 文件展示区域 - 更美观的设计 -->
    <view v-if="hasAnyFiles" class="files-showcase">
      <!-- 图片文件展示区 -->
      <view v-if="imageFiles.length > 0" class="file-type-section">
        <view class="type-header">
          <view class="type-title">
            <fui-icon
              name="picture"
              color="#0052d9"
              :size="20"
            ></fui-icon>
            <text>图片 ({{ imageFiles.length }})</text>
          </view>
          
        </view>
        <view class="file-grid">
          <view
            v-for="(file, index) in imageFiles"
            :key="file.id"
            class="file-item image-item"
          >
            <image
              :src="file.fileUrl"
              mode="aspectFill"
              class="file-thumbnail"
              @tap="previewImage(file.fileUrl, imageFiles.map(img => img.fileUrl))"
            />
            <view class="file-actions">
              <view class="action-btn delete" @tap="handleDeleteMedia(file.id, 'image')">
                <fui-icon name="close" color="#fff" :size="30"></fui-icon>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 文档文件展示区 -->
      <view v-if="documentFiles.length > 0" class="file-type-section">
        <view class="type-header">
          <view class="type-title">
            <fui-icon
              name="order"
              color="#0052d9"
              :size="20"
            ></fui-icon>
            <text>文档 ({{ documentFiles.length }})</text>
          </view>
          
        </view>
        <view class="file-list">
          <view
            v-for="(file, index) in documentFiles"
            :key="file.id"
            class="doc-item"
            @tap="previewFile(file.fileUrl, file.originalName)"
          >
            <view class="doc-icon">
              <text :class="getFileIconByExt(file.originalName)"></text>
            </view>
            <view class="doc-info">
              <text class="doc-name">{{ getShortenedFileName(file.originalName) }}</text>
              <text class="doc-type">{{ getFileTypeLabel(file.originalName) }}</text>
            </view>
            <view class="doc-actions">
              <view
                class="action-btn delete"
                @tap.stop="handleDeleteFile(file.id, index)"
              >
              <fui-icon name="close" color="#fff" :size="30"></fui-icon>

              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 视频文件展示区 -->
      <view v-if="videoFiles.length > 0" class="file-type-section">
        <view class="type-header">
          <view class="type-title">
            <fui-icon
              name="video"
              color="#0052d9"
              :size="20"
            ></fui-icon>
            <text>视频 ({{ videoFiles.length }})</text>
          </view>
          
        </view>
        <view class="file-grid">
          <view
            v-for="(file, index) in videoFiles"
            :key="file.id"
            class="file-item video-item"
          >
            <video
              :src="file.fileUrl"
              class="video-thumbnail"
              :poster="file.poster || ''"
              :controls="false"
              :show-play-btn="false"
              :enable-progress-gesture="false"
              @tap="previewFile(file.fileUrl, file.originalName)"
            ></video>
            
            <text class="video-duration">{{ getDurationLabel(index) }}</text>
            <view class="file-actions">
              <view class="action-btn delete" @tap="handleDeleteMedia(file.id, 'video')">
                <fui-icon name="close" color="#fff" :size="30"></fui-icon>

              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, onMounted, watch } from 'vue';
// 数据示例
const demo = [
  {
    "filePath": "/upload/company/archival/2025-05-20/603web开发课程视频.mp4",
    "fileType": "video",
    "fileUrl": "https://assess.yuejin-tech.com/upload/company/archival/2025-05-20/603web开发课程视频.mp4",
    "id": "file_1747749039185_872",
    "originalName": "603web开发课程视频",
    "progress": 100,
    "uploading": false
  },
  {
    "filePath": "/upload/company/archival/2025-05-20/755高级web开发课程设计.docx",
    "fileType": "file",
    "fileUrl": "https://assess.yuejin-tech.com/upload/company/archival/2025-05-20/755高级web开发课程设计.docx",
    "id": "file_1747749035380_163",
    "originalName": "9acbee1c-39d8-4949-9e8c-0387e3c5de92",
    "progress": 100,
    "uploading": false
  },
  {
    "filePath": "/upload/company/archival/2025-05-20/147u=2265047174,3117414710&fm=253&fmt=auto&app=138&f=JPEG.webp",
    "fileType": "image",
    "fileUrl": "https://assess.yuejin-tech.com/upload/company/archival/2025-05-20/147u=2265047174,3117414710&fm=253&fmt=auto&app=138&f=JPEG.webp",
    "id": "file_1747749031376_909",
    "originalName": "a058cb5d-94ed-494d-b324-ea01c2fb42ee",
    "progress": 100,
    "uploading": false
  }
]

// --- Constants ---
const hostUrl = "https://assess.yuejin-tech.com"; // Ensure no trailing slash
const imageUploadUrl = `${hostUrl}${props.uploadUrl}`;
const fileUploadUrl = `${hostUrl}${props.uploadUrl}`;
const videoUploadUrl = `${hostUrl}${props.uploadUrl}`;

// Use publicly accessible and reliable icon URLs
const pdfIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_acrobat.png";
const wordIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_word.png";
const excelIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_excel.png";
const pptIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white_powerpoint.png";
const genericFileIconUrl = "https://cdnjs.cloudflare.com/ajax/libs/fatcow-icons/20130425/FatCow_Icons32x32/page_white.png";


const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  // 新增：初始图片数组
  initialImages: {
    type: Array,
    default: () => []
  },
  // 新增：初始视频数组
  initialVideos: {
    type: Array,
    default: () => []
  },
  // 新增：初始文件数组
  initialFiles: {
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: '附件'
  },
  required: {
    type: Boolean,
    default: false
  },
  maxImageCount: {
    type: Number,
    default: 9
  },
  maxFileCount: {
    type: Number,
    default: 5
  },
  maxVideoCount: {
    type: Number,
    default: 3
  },
  maxTotalFiles: {
    type: Number,
    default: 15
  },
  uploadUrl: {
    type: String,
    default: '/api/upload'
  }
});


const emit = defineEmits(['update:modelValue']);

// 初始化组件时，将初始文件添加到modelValue中
const initializeFiles = () => {
  // 处理初始图片
const initialImageFiles = Array.isArray(props.initialImages)
  ? props.initialImages.map(url => ({
      id: generateUniqueId(),
      fileUrl: url,
      fileType: 'image',
      originalName: getOriginalNameFromUrl(url),
      filePath: url.replace(/^https?:\/\/[^\/]+/, ''),
      progress: 100,
      uploading: false
    }))
  : [];

// 处理初始视频
const initialVideoFiles = Array.isArray(props.initialVideos)
  ? props.initialVideos.map(url => ({
      id: generateUniqueId(),
      fileUrl: url,
      fileType: 'video',
      originalName: getOriginalNameFromUrl(url),
      filePath: url.replace(/^https?:\/\/[^\/]+/, ''),
      progress: 100,
      uploading: false
    }))
  : [];

// 处理初始文件
const initialDocFiles = Array.isArray(props.initialFiles)
  ? props.initialFiles.map(url => ({
      id: generateUniqueId(),
      fileUrl: url,
      fileType: 'file',
      originalName: getOriginalNameFromUrl(url),
      filePath: url.replace(/^https?:\/\/[^\/]+/, ''),
      progress: 100,
      uploading: false
    }))
  : [];

  // 合并所有初始文件
  if (initialImageFiles.length > 0 || initialVideoFiles.length > 0 || initialDocFiles.length > 0) {
    const initialFiles = [...initialImageFiles, ...initialVideoFiles, ...initialDocFiles];
    // 如果modelValue为空，则直接设置，否则合并
    if (props.modelValue.length === 0) {
      emit('update:modelValue', initialFiles);
    } else {
      // 避免重复添加
      const existingUrls = props.modelValue.map(file => file.fileUrl);
      const newFiles = initialFiles.filter(file => !existingUrls.includes(file.fileUrl));
      if (newFiles.length > 0) {
        emit('update:modelValue', [...props.modelValue, ...newFiles]);
      }
    }
  }
};

// 从URL中提取原始文件名
const getOriginalNameFromUrl = (url) => {
  if (!url) return '';
  
  // 从URL中提取文件名部分
  const urlParts = url.split('/');
  const fileNameWithParams = urlParts[urlParts.length - 1];
  
  // 移除可能的URL参数
  const fileName = fileNameWithParams.split('?')[0];
  
  // 提取文件名中的实际部分（去除UUID格式名称）
  // 示例：553消防.png 或 603web开发课程视频.mp4 或 755高级web开发课程设计.docx
  // 移除前面的数字部分，保留实际名称
  const match = fileName.match(/^\d+(.+)$/);
  return match ? match[1] : fileName;
};

// 在组件挂载后初始化文件
onMounted(() => {
  initializeFiles();
});

// 监听初始文件属性变化
watch([() => props.initialImages, () => props.initialVideos, () => props.initialFiles], () => {
  initializeFiles();
}, { deep: true });

// 计算属性：按类型分类文件
const imageFiles = computed(() => {
  return props.modelValue.filter(file => file.fileType === 'image');
});

const documentFiles = computed(() => {
  return props.modelValue.filter(file => file.fileType === 'file');
});

const videoFiles = computed(() => {
  return props.modelValue.filter(file => file.fileType === 'video');
});

// 计算是否达到各类型文件上限
const isImageLimitReached = computed(() => {
  return imageFiles.value.length >= props.maxImageCount;
});

const isFileLimitReached = computed(() => {
  return documentFiles.value.length >= props.maxFileCount;
});

const isVideoLimitReached = computed(() => {
  return videoFiles.value.length >= props.maxVideoCount;
});

const isTotalLimitReached = computed(() => {
  return props.modelValue.length >= props.maxTotalFiles;
});

const hasAnyFiles = computed(() => {
  return props.modelValue.length > 0;
});

// --- Helper Functions ---
// 生成唯一ID
const generateUniqueId = () => {
  return 'file_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
};

// 根据文件扩展名获取对应的图标
const getFileIconByExt = (filename) => {
  const lowerCaseName = filename.toLowerCase();
  if (lowerCaseName.endsWith(".pdf")) return pdfIconUrl;
  else if (lowerCaseName.endsWith(".doc") || lowerCaseName.endsWith(".docx"))
    return wordIconUrl;
  else if (lowerCaseName.endsWith(".xls") || lowerCaseName.endsWith(".xlsx"))
    return excelIconUrl;
  else if (lowerCaseName.endsWith(".ppt") || lowerCaseName.endsWith(".pptx"))
    return pptIconUrl;
  else return genericFileIconUrl;

  // 如果需要使用图标字体，可以使用下面的代码
  // const ext = filename.split('.').pop().toLowerCase();
  // const iconMap = {
  //   pdf: 'cicon-pdf',
  //   doc: 'cicon-word', docx: 'cicon-word',
  //   xls: 'cicon-excel', xlsx: 'cicon-excel',
  //   ppt: 'cicon-ppt', pptx: 'cicon-ppt',
  //   zip: 'cicon-zip', rar: 'cicon-zip', '7z': 'cicon-zip',
  //   txt: 'cicon-txt',
  // };
  // return iconMap[ext] || 'cicon-file';
};

// 获取简短文件名（如果过长）
const getShortenedFileName = (filename, maxLength = 10) => {
  if (!filename) return '';
  
  // 如果文件名是UUID格式，尝试提取真实文件名
  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(filename)) {
    // 这是UUID格式，尝试从URL或其他属性中获取真实文件名
    return '未知文件';
  }
  
  // 检查是否有数字前缀（如553消防.png）
  const match = filename.match(/^\d+(.+)$/);
  const realName = match ? match[1] : filename;
  
  if (realName.length <= maxLength) return realName;

  const ext =
    realName.lastIndexOf(".") > 0
      ? realName.substring(realName.lastIndexOf("."))
      : "";
  const nameWithoutExt = realName.substring(
    0,
    realName.lastIndexOf(".") > 0 ? realName.lastIndexOf(".") : realName.length
  );

  if (ext.length >= maxLength - 3) {
    return `...${ext}`;
  }

  const availableChars = maxLength - 3 - ext.length;
  return `${nameWithoutExt.substring(0, availableChars)}...${ext}`;
};

// 预览图片
const previewImage = (url, urls) => {
  if (!url) return;
  
  uni.previewImage({
    current: url,
    urls: urls || [url],
    indicator: 'number',
    loop: true,
    fail: (err) => {
      console.error('预览图片失败:', err);
    }
  });
};

// 预览文件
const previewFile = (url, name) => {
  if (!url) return;
  
  // 对于PDF等可以预览的文件
  uni.downloadFile({
    url: url,
    success: (res) => {
      if (res.statusCode === 200) {
        const tempFilePath = res.tempFilePath;
        uni.openDocument({
          filePath: tempFilePath,
          fail: (err) => {
            console.error('打开文件失败:', err);
            uni.showToast({ title: '此文件类型无法在线预览', icon: 'none' });
          },
        });
      }
    },
    fail: (err) => {
      console.error('下载文件失败:', err);
      uni.showToast({ title: '下载文件失败', icon: 'none' });
    },
  });
};

// 根据文件类型获取标签
const getFileTypeLabel = (filename) => {
  if (!filename) return '';
  
  const ext = filename.split('.').pop().toLowerCase();
  const typeMap = {
    pdf: 'PDF文档',
    doc: 'Word文档', docx: 'Word文档',
    xls: 'Excel表格', xlsx: 'Excel表格',
    ppt: 'PPT演示', pptx: 'PPT演示',
    txt: '文本文档',
    zip: '压缩文件', rar: '压缩文件', '7z': '压缩文件',
    jpg: '图片', jpeg: '图片', png: '图片', gif: '图片',
    mp4: '视频', mov: '视频', avi: '视频', mkv: '视频'
  };
  
  return typeMap[ext] || ext.toUpperCase() + '文件';
};

// 获取视频时长显示
const getDurationLabel = (index) => {
  // 这里可以根据实际情况获取视频时长
  // 示例返回固定时长
  return '00:30';
};

// --- Delete Logic ---
// 处理删除
const handleDelete = (fileId) => {
  const updatedFiles = props.modelValue.filter(file => file.id !== fileId);
  emit('update:modelValue', updatedFiles);
};

// 专门处理文件删除，增加确认对话框
const handleDeleteFile = (fileId, index) => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除此文件吗？',
    success: (res) => {
      if (res.confirm) {
        handleDelete(fileId);
      }
    }
  });
};

// 处理图片和视频删除
const handleDeleteMedia = (fileId, type) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除此${type === 'image' ? '图片' : '视频'}吗？`,
    success: (res) => {
      if (res.confirm) {
        handleDelete(fileId);
      }
    }
  });
};

// --- Upload Logic ---
// 选择图片
const handleChooseImage = () => {
  if (isImageLimitReached.value || isTotalLimitReached.value) {
    uni.showToast({
      title: isImageLimitReached.value ? '图片数量已达上限' : '附件总数已达上限',
      icon: 'none'
    });
    return;
  }
  
  chooseAndUploadImage();
};

// 选择并上传图片
const chooseAndUploadImage = () => {
  uni.chooseImage({
    count: Math.min(
      props.maxImageCount - imageFiles.value.length,
      props.maxTotalFiles - props.modelValue.length
    ),
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      const tempFiles = res.tempFiles;
      
      // 上传每张图片
      tempFilePaths.forEach((path, index) => {
        const originalName = path.split('/').pop();
        uploadToServer(path, imageUploadUrl, 'image', originalName || `image_${index}.jpg`);
      });
    },
    fail: (err) => {
      if (err.errMsg !== 'chooseImage:fail cancel') {
        handleChooseFail('图片');
      }
    }
  });
};

// 选择文件
const handleChooseFile = () => {
  if (isFileLimitReached.value || isTotalLimitReached.value) {
    uni.showToast({
      title: isFileLimitReached.value ? '文档数量已达上限' : '附件总数已达上限',
      icon: 'none'
    });
    return;
  }
  
  chooseAndUploadFile();
};

// 选择并上传文件
const chooseAndUploadFile = () => {
  const availableFileSlots = props.maxFileCount - documentFiles.value.length;
  const availableTotalSlots = props.maxTotalFiles - props.modelValue.length;
  // count is already guaranteed to be > 0 by handleChooseFile (the caller)
  const count = Math.min(availableFileSlots, availableTotalSlots);

  // #ifdef MP-WEIXIN
  wx.chooseMessageFile({
    count: count,
    type: 'file', // Options: 'all', 'video', 'image', 'file'. 'file' is for general documents.
    success: (res) => {
      const tempFiles = res.tempFiles; // Array of {path, name, size, type, time}
      tempFiles.forEach(file => {
        const originalName = file.name || `file-${Date.now()}`;
        uploadToServer(file.path, fileUploadUrl, 'file', originalName);
      });
    },
    fail: (err) => {
      // Check for user cancellation (errMsg varies by platform/API)
      if (!(err.errMsg && err.errMsg.includes('cancel'))) {
        handleChooseFail('文件');
      }
    }
  });
  // #else // For platforms OTHER than MP-WEIXIN
    // #if defined(APP-PLUS) || defined(H5)
    uni.chooseFile({
      count: count,
      extension: [ // Extension filtering for platforms that support it
        '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
        '.txt', '.zip', '.rar', '.7z'
      ],
      success: (res) => {
        const tempFiles = res.tempFiles; // Array of {name, path, size}
        tempFiles.forEach(file => {
          const originalName = file.name || (file.path ? file.path.split('/').pop() : `file-${Date.now()}`);
          uploadToServer(file.path, fileUploadUrl, 'file', originalName);
        });
      },
      fail: (err) => {
        if (!(err.errMsg && err.errMsg.includes('cancel'))) {
          handleChooseFail('文件');
        }
      }
    });
    // #elif defined(MP-ALIPAY) // Specific handling for Alipay
    uni.showToast({
      title: '支付宝小程序暂不支持选择文件',
      icon: 'none'
    });
    // #elif defined(MP-BAIDU) || defined(MP-TOUTIAO) || defined(MP-QQ) || defined(MP-KUAISHOU) // Specific handling for other MPs
    uni.showToast({
      title: '当前平台暂不支持选择文件',
      icon: 'none'
    });
    // #else
    // Optional: Fallback for any other unhandled platforms.
    // console.log('File choosing not configured for this platform.');
    // #endif
  // #endif // End of #ifndef MP-WEIXIN
};

// 选择视频
const handleChooseVideo = () => {
  if (isVideoLimitReached.value || isTotalLimitReached.value) {
    uni.showToast({
      title: isVideoLimitReached.value ? '视频数量已达上限' : '附件总数已达上限',
      icon: 'none'
    });
    return;
  }
  
  chooseAndUploadVideo();
};

// 选择并上传视频
const chooseAndUploadVideo = () => {
  uni.chooseVideo({
    sourceType: ['album', 'camera'],
    compressed: true,
    maxDuration: 60,
    camera: 'back',
    success: (res) => {
      const tempFilePath = res.tempFilePath;
      const originalName = tempFilePath.split('/').pop() || `video_${Date.now()}.mp4`;
      uploadToServer(tempFilePath, videoUploadUrl, 'video', originalName);
    },
    fail: (err) => {
      if (err.errMsg !== 'chooseVideo:fail cancel') {
        handleChooseFail('视频');
      }
    }
  });
};

// 通用选择失败处理
const handleChooseFail = (type) => {
  uni.showToast({
    title: `选择${type}失败，请重试`,
    icon: 'none'
  });
};

// 通用上传函数
const uploadToServer = (tempFilePath, url, type, originalName) => {
  // 显示上传中
  uni.showLoading({
    title: '上传中...',
    mask: true
  });
  
  // 创建临时文件对象用于UI展示
  const tempFile = {
    id: generateUniqueId(),
    fileUrl: tempFilePath,
    fileType: type,
    originalName: originalName,
    uploading: true,
    progress: 0
  };
  
  // 添加到文件列表中
  const updatedFiles = [...props.modelValue, tempFile];
  emit('update:modelValue', updatedFiles);
  
  // 根据文件类型选择上传URL
  let uploadUrl;
  switch (type) {
    case 'image':
      uploadUrl = imageUploadUrl;
      break;
    case 'video':
      uploadUrl = videoUploadUrl;
      break;
    case 'file':
      uploadUrl = fileUploadUrl;
      break;
    default:
      uploadUrl = url || imageUploadUrl;
  }
  
  // 执行上传
  const uploadTask = uni.uploadFile({
    url: uploadUrl, // 直接使用完整URL而不是sheep.$url.api(url)
    filePath: tempFilePath,
    name: 'file',
    formData: {
      type: type,
      filename: originalName
    },
    success: (uploadRes) => {
      try {
        // 解析响应数据
        const data = JSON.parse(uploadRes.data);
        
        if (data.code === 0 || data.code === 200) {
          // 上传成功，更新文件信息
          const fileInfo = data.data;
          // 找到临时文件并更新
          const finalFiles = props.modelValue.map(file => {
            if (file.id === tempFile.id) {
              return {
                ...file,
                id: fileInfo.id || file.id,
                fileUrl: fileInfo || file.fileUrl,
                filePath: fileInfo.replace(/^https?:\/\/[^\/]+/, "") || file.fileUrl,
                originalName: fileInfo.originalName || file.originalName,
                uploading: false,
                progress: 100
              };
            }
            return file;
          });
          console.log('上传成功：', finalFiles);
          
          emit('update:modelValue', finalFiles);
          
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          });
        } else {
          // 上传失败，移除临时文件
          const filteredFiles = props.modelValue.filter(file => file.id !== tempFile.id);
          emit('update:modelValue', filteredFiles);
          
          uni.showToast({
            title: data.msg || '上传失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error('解析上传响应失败:', e);
        
        // 解析失败，移除临时文件
        const filteredFiles = props.modelValue.filter(file => file.id !== tempFile.id);
        emit('update:modelValue', filteredFiles);
        
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('上传失败:', err);
      
      // 上传失败，移除临时文件
      const filteredFiles = props.modelValue.filter(file => file.id !== tempFile.id);
      emit('update:modelValue', filteredFiles);
      
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
  
  // 监听上传进度
  uploadTask.onProgressUpdate((res) => {
    // 更新进度
    const progressFiles = props.modelValue.map(file => {
      if (file.id === tempFile.id) {
        return {
          ...file,
          progress: res.progress
        };
      }
      return file;
    });
    
    emit('update:modelValue', progressFiles);
  });
};
</script>

<style lang="scss" scoped>
.attachments-section {
  margin-bottom: 40rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title-wrapper {
  display: flex;
  align-items: center;
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #4f4e4e;
}

.required-mark {
  color: #ff4d4f;
  margin-left: 4rpx;
}

.upload-stats {
  display: flex;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-left: 16rpx;
  font-size: 24rpx;
  color: #0052d9;
}

.stat-item.limit-reached {
  color: #c0c4cc;
}

.upload-triggers-modern {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.trigger-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20rpx 0;
  margin: 0 10rpx;
  background-color: #f5f7fa;
  border-radius: 8rpx;
  transition: all 0.3s;
}

.trigger-btn:first-child {
  margin-left: 0;
}

.trigger-btn:last-child {
  margin-right: 0;
}

.trigger-btn:active {
  background-color: #e9ecf2;
}

.trigger-btn.disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.btn-icon {
  margin-bottom: 10rpx;
}

.btn-text {
  font-size: 24rpx;
  color: #0052d9;
}

.btn-text.disabled-text {
  color: #c8c9cc;
}

.empty-attachments-modern {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  background-color: #f5f7fa;
  border-radius: 8rpx;
}

.empty-icon {
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #909399;
}

.files-showcase {
  margin-top: 20rpx;
}

.file-type-section {
  margin-bottom: 30rpx;
}

.type-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.type-title {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #1a1a1a;
}

.type-title text {
  margin-left: 8rpx;
}

.type-action {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #0052d9;
}

.type-action text {
  margin-left: 4rpx;
}

.file-grid {
  display: flex;
  flex-wrap: wrap;
}

.file-item {
  position: relative;
  width: 220rpx;
  height: 220rpx;
  margin-right: 15rpx;
  margin-bottom: 15rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.file-item:nth-child(3n) {
  margin-right: 0;
}

.file-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-actions {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  display: flex;
}

.action-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin-left: 8rpx;
}

.action-btn.delete {
  background-color: rgba(0, 0, 0, 0.5);
}

.file-list {
  background-color: #f5f7fa;
  border-radius: 8rpx;
  padding: 10rpx 0;
}

.doc-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1px solid #ebeef5;
}

.doc-item:last-child {
  border-bottom: none;
}

.doc-icon {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.doc-icon text {
  font-size: 60rpx;
  color: #0052d9;
}

.doc-info {
  flex: 1;
  overflow: hidden;
}

.doc-name {
  font-size: 28rpx;
  color: #1a1a1a;
  margin-bottom: 6rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.doc-type {
  font-size: 24rpx;
  color: #909399;
}

.doc-actions {
  display: flex;
  align-items: center;
}

.video-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
}

.video-duration {
  position: absolute;
  bottom: 8rpx;
  right: 8rpx;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 4rpx;
}
</style>